//
//  Durable subscriber
//

package main

import (
	"fmt"
	"os"
	"zmq"
)

func zmq_main() os.Error {
	context, err := zmq.Init(1)
	if err != nil {
		return err
	}
	defer context.Close()

	subscriber, err := context.Socket(zmq.SUB)
	if err != nil {
		return err
	}
	defer subscriber.Close()
	err = subscriber.SetOptionVal(zmq.IDENTITY, "Hello")
	if err != nil {
		return err
	}
	err = subscriber.SetOptionVal(zmq.SUBSCRIBE, "")
	if err != nil {
		return err
	}

	err = subscriber.Connect("tcp://localhost:5565")
	if err != nil {
		return err
	}

	sync, err := context.Socket(zmq.PUSH)
	if err != nil {
		return err
	}
	defer sync.Close()

	err = sync.Connect("tcp://localhost:5564")
	if err != nil {
		return err
	}

	err = sync.Send([]byte("sync"), 0)
	if err != nil {
		return err
	}
	msg, err := zmq.InitMsg()
	if err != nil {
		return err
	}
	defer msg.Close()
	for {
		data, err := subscriber.RecvMsg(msg, 0)
		if err != nil {
			return err
		}
		fmt.Println(string(data))
		if string(data) == "END" {
			break
		}
	}
	return nil
}

var errch = make(chan os.Error)

func main() {
	fmt.Println("Durable subscriber")
	exit := make(chan bool)
	go func() {
		for {
			err := <-errch
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		}
	}()
	go func() {
		err := zmq_main()
		if err != nil {
			errch <- err
		} else {	
			exit <- true
		}
	}()
	<-exit
}
